package common.intercepter.service;


import cn.hutool.core.util.StrUtil;
import common.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class TsgyunAuthorizingService {

    @Resource
    HttpSession session;

    @Resource
    HttpServletRequest request;

    @Resource
    HttpServletResponse response;

    @Resource
    CacheUtil cacheUtil;

    @Resource
    TokenAuthorizingService tokenAuthService;

    //获取名为userinfo的tsgyun.com的相应cookie
    private Cookie filterTsguserCookie(Cookie[] cookies) {
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                String cookieName = cookie.getName();
                if (cookieName.equals("tsguser")) {
//                    System.out.println("存在tsg云用户信息:" + cookie.getValue());
                    return cookie;
                }
            }
        }
        return null;
    }

    public Boolean decryptCookie(Cookie[] cookies) {
        Cookie userInfoCookie = filterTsguserCookie(cookies);
        if (userInfoCookie == null) {
            return false;
        }
        String userinfo = userInfoCookie.getValue();
//        log.info("实际cookie的value:"+userinfo);
        if (StrUtil.isEmpty(userinfo)) {
            log.info("cookie为空!!!!");
            return false;
        }
        try {
            return tokenAuthService.decryptToken(userinfo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

}
